package cn.com.yang.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 在释放等待线程后可以重用，所以称为循环barrier
 * CyclicBarrier支持一个可选的Runnable，在计数器的值到达设定值后（但在释放所有线程之前），
 * 该Runnable运行一次。注：Runnable在每个屏障点只运行一个。
 * @author 杨亿金
 * @date 2022年8月31日-下午8:05:00
 * @since 1.0.0
 */
public class TestCyclicBarrier {
	
	
	public static void main(String[] args) throws InterruptedException {
		int threads = 5;
		CyclicBarrier barrier = new CyclicBarrier(threads, ()-> {
			//所有参与线程都执行到完了，合并结果处理
			System.out.println("callback is runing");
		});
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 0; i < threads; i++) {
			final int threadNum = i;
			Thread.sleep(1000);
			executorService.execute(()->{
				try {
					Thread.sleep(1000);
					System.out.println("running is ready"+threadNum);
					//每个线程都调用这个，等待执行完成，相互阻塞
					barrier.await();
					System.out.println("thread is continue "+threadNum);
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		}
		executorService.shutdown();
	}
}
